package cn.htcode.controller;

import cn.htcode.domain.User;
import cn.htcode.mapper.UserMapper;
import cn.htcode.service.ILoginService;
import cn.htcode.service.imp.LoginImpl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * @author: Mr_he
 * @Version:1.0
 */
@WebServlet("/login")
public class LoginConturller extends HttpServlet {

    private UserMapper userMapper;

//    @Override
//    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        String account = req.getParameter("account");
//        String password = req.getParameter("password");
//        //用户登录操作
//        ILoginService iLoginService = new LoginImpl();
//        User login = iLoginService.login(account, password);
//        //userMapper.login(account, password);
//        if (login == null) {
//            req.getRequestDispatcher("/login.html").forward(req, resp);
//            return;
//        }
//        req.getSession().setAttribute("login", login);
//        req.getRequestDispatcher("/product.html").forward(req, resp);
//    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedReader reader = req.getReader();
        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree(sb.toString());
        String account = jsonNode.get("account").asText();
        String password = jsonNode.get("password").asText();

        //用户登录操作
        ILoginService iLoginService = new LoginImpl();
        User login = iLoginService.login(account, password);

        //userMapper.login(account, password);
        if (login == null) {
            req.getRequestDispatcher("/login.html").forward(req, resp);
            return;
        }
        req.getSession().setAttribute("user", login);
        req.getRequestDispatcher("/product.html").forward(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/login.html").forward(req, resp);
    }
}
